#define WIN32_LEAN_AND_MEAN
#include "StdAfx.h"
#include <windows.h>
//#include <ShellAPI.h>
#include "shlwapi.h"
#pragma comment(lib, "shlwapi.lib")

#include "IGameStartup.h"

//////////////////////////////////////////////////////////////////////////
// Initializes Root folder of the game.
//////////////////////////////////////////////////////////////////////////
void InitWorkDirectory()
{
#ifdef WIN32
	WCHAR szExeFileName[_MAX_PATH];

	GetModuleFileNameW( GetModuleHandle(NULL), szExeFileName, sizeof(szExeFileName));
	PathRemoveFileSpecW(szExeFileName);

	// Remove Bin folder
	WCHAR *lpPath = StrStrIW(szExeFileName,L"\\Bin");
	if (lpPath)
		*lpPath = 0;

	SetCurrentDirectoryW( szExeFileName );
#endif
}

int RunGame(const char *commandLine)
{
	HANDLE mutex = CreateMutex(NULL, TRUE, "VisualImpactApplication");
	if (GetLastError() == ERROR_ALREADY_EXISTS)
	{
		if(MessageBox(GetDesktopWindow(), "There is already a VisualImpact application running.\nDo you want to start another one?", "Too many apps", MB_YESNO)!=IDYES)
		{
			return 1;
		}
	}

	InitWorkDirectory();

	// load the game dll
	HMODULE gameDll = LoadLibrary( "ParallelWorld.dll" );
	if (!gameDll)
	{
		MessageBox(NULL, "Failed to load the Game DLL!", "Error", MB_OK | MB_DEFAULT_DESKTOP_ONLY);
	}

	// get address of startup function
	IGameStartup::TEntryFunction CreateGameStartup = (IGameStartup::TEntryFunction)GetProcAddress(gameDll, "CreateGameStartup");

	if (!CreateGameStartup)
	{
		// dll is not a compatible game dll
		FreeLibrary(gameDll);

		MessageBox(0, "Specified Game DLL is not valid!", "Error", MB_OK | MB_DEFAULT_DESKTOP_ONLY);

		CloseHandle(mutex);
		
		return 0;
	}

	// create the startup interface
	IGameStartup *pGameStartup = CreateGameStartup();

	if (!pGameStartup)
	{
		// failed to create the startup interface
		FreeLibrary(gameDll);

		MessageBox(0, "Failed to create the GameStartup Interface!", "Error", MB_OK | MB_DEFAULT_DESKTOP_ONLY);

		CloseHandle(mutex);

		return 0;
	}

	// run the game
	if (pGameStartup->Init())
	{
		pGameStartup->Run(NULL);

		pGameStartup->Shutdown();

		pGameStartup = NULL;

		FreeLibrary(gameDll);
	}

	CloseHandle(mutex);

	return 0;
}

///////////////////////////////////////////////
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	int nRes = RunGame(GetCommandLineA());

	return 0;
}